package com.example.demo.others.jenkins;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.confi.JenkinsConf;
import com.example.demo.others.git.AutoPushUtil;
import com.offbytwo.jenkins.JenkinsServer;
import com.offbytwo.jenkins.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Created by Administrator on 2017/3/17 0017.
 */

@Component
public class Jenkins {

    private static String base_jenkins_url;

    @Value("${base_jenkins_url}")
    public void setBase_jenkins_url(String base_jenkins_url) {
        Jenkins.base_jenkins_url = base_jenkins_url;
    }

    static Logger logger = LoggerFactory.getLogger(Jenkins.class);

    public static void run(String name, String pack) throws Exception {
        Jenkins fastTestJenkinsService = new Jenkins();


        int jobId = fastTestJenkinsService.buildJob(name, pack);


    }


    /**
     *
     */
    public int buildJob(String name, String pack) throws Exception {

        int buildNumber = 0;

        JenkinsServer jenkinsServer = jenkins(name);
        Map<String, Job> jobs = jenkinsServer.getJobs();
        jobs.forEach((k, v) -> {

            try {


                if (!k.startsWith("build")) return;
//                if (k.contains(""))
//                    logger.info("{},{} ,{}", k, v.getUrl());

                List<JSONObject> li = JenkinsConf.models.stream().filter(m -> {
                    return m.getString("pack").equals(pack);
                }).collect(Collectors.toList());
                if (li == null || li.isEmpty()) return;
                JSONObject j = li.get(0);
                ;
                if (j != null && j.getString("model").equals(k)) {


                    String url = v.getUrl() + "ws/" + j.getString("download") + "/target/" + pack;

                    try {
                        InputStream in = v.getClient().getFile(URI.create(url));
                        logger.info("download file :{} start", pack);
                        Files.copy(in, Paths.get(AutoPushUtil.base_source_dir + pack), StandardCopyOption.REPLACE_EXISTING);
                        logger.info("download file :{} success", pack);

                    } catch (Exception e) {

                        e.printStackTrace();
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });


        logger.info("qr:{}", 1);

        return buildNumber;
    }

    public static List<String> dabao(String name, String pack, Map<String, String> branch) {

        int buildNumber = 0;

        List<String> msg = new ArrayList<>();
        try {
            JenkinsServer jenkinsServer = jenkins(name);// new JenkinsServer(new URI("http://jenkins.dev-mycp.com"), "caixingdu", "Caixs$1356");
            Map<String, Job> jobs = jenkinsServer.getJobs();
            jobs.forEach((k, v) -> {

                try {
                    if (!k.startsWith("build")) return;
                    List<JSONObject> li = JenkinsConf.models.stream().filter(m -> {
                        return m.getString("pack").equals(pack);
                    }).collect(Collectors.toList());
                    if (li == null || li.isEmpty()) return;
                    JSONObject j = li.get(0);
                    ;
                    if (j != null && j.getString("model").equals(k)) {
                        JenkinsUtil.job(v, branch);
//                        v.
                        while (true) {
                            ;
                            boolean run = v.details().getLastBuild().details().isBuilding();
                            if (!run) {

                                BuildWithDetails build = v.details().getLastBuild().details();
                                try {
                                    String mg = build.getResult().toString();



                                 String task =    build.getFullDisplayName();
                                 long dur =   build.getDuration();
                                    msg.add("task:" +task+"   haoshi:" + dur+"  result:"+mg);

                                } catch (Exception ee) {

                                }

                                return;
                            } else {
                                logger.info("building");

                                TimeUnit.SECONDS.sleep(1);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });


            logger.info("qr:{}", 1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return msg;
    }

    public static List<String> deploy(String name, String jobName, Map<String, String> branch) {

        int buildNumber = 0;

        List<String> msg = new ArrayList<>();
        try {
            JenkinsServer jenkinsServer = jenkins(name);// new

            Job v = jenkinsServer.getJob(jobName);
            JenkinsUtil.job(v, branch);
            while (true) {
                ;
                boolean run = v.details().getLastBuild().details().isBuilding();
                if (!run) {
                    msg.add("success");
                    break;
                } else {
                    logger.info("building");
                    TimeUnit.SECONDS.sleep(1);
                }
            }
            logger.info("qr:{}", 1);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
        return msg;
    }


    public static Map<String, JenkinsServer> jenkinsServers = new HashMap<>();


    public static String addJenkins(String name, String pwd) {
        try {
            JenkinsServer j = new JenkinsServer(new URI(base_jenkins_url), name, pwd);
            j.getJob("");
            jenkinsServers.put(name, j);
            return "";
        } catch (Exception e) {

            logger.info("msg , {}", e.getMessage());
            return "jenkins: " + e.getMessage();
        }


    }

    public static JenkinsServer jenkins(String name) {
        try {
            return jenkinsServers.get(name);
        } catch (Exception e) {

        }

        return null;
    }
}
